package com.example.xianji;

import android.app.Application;
import android.content.Intent;
import android.os.Build;
import android.os.StrictMode;
import android.util.Log;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.example.xianji.activity.MainActivity;
import com.example.xianji.utils.sp.PreferenceEngine;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.tauth.Tencent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class XJApplication extends Application implements Thread.UncaughtExceptionHandler{
    public static RequestQueue queues;
    private static XJApplication sAppInstance;
    public static ExecutorService cachThreadPool;

    public static IWXAPI api;
    public static Tencent mTencent;
    public static AuthInfo mAuthInfo;
//    public static  RefWatcher refWatcher;

    public static XJApplication getInstance() {
        return sAppInstance;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        sAppInstance = this;
        /**
         * 程序崩溃检测
         */
        Thread.setDefaultUncaughtExceptionHandler(this);

        //	this.refWatcher = LeakCanary.install(this);

        /**
         * 没有再抛出FileUriExposedException
         * 某些应用（此处点名新浪微博）根本无法理解一个指向文件的content://格式的URI
         */
        if (Build.VERSION.SDK_INT >= 24) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }

        //初始化SharedPreference
        PreferenceEngine.getInstance().init(this);

        // 获取APP ID并将以下代码复制到项目Application类onCreate()中，Bugly会为自动检测环境并完成配置：

        CrashReport.initCrashReport(getApplicationContext(), "fcca3288a1", false);
        queues = Volley.newRequestQueue(getApplicationContext());
        cachThreadPool = Executors.newFixedThreadPool(15);
        //微信 wx335612fd5a4203d5
        api = WXAPIFactory.createWXAPI(getApplicationContext(),
                "wx79e902dceb15b8bb");
        api.registerApp("wx79e902dceb15b8bb");

        // x5内核初始化接口
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

            @Override
            public void onViewInitFinished(boolean arg0) {
                // x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                // Toast.makeText(getApplicationContext(), arg0+"ddddd",
                // 0).show();
                Log.d("app", " onViewInitFinished is " + arg0);
            }

            @Override
            public void onCoreInitFinished() {
            }
        };
        // x5内核初始化接口
        QbSdk.initX5Environment(getApplicationContext(), cb);

        /** QQ"1105655511","101211617" **/
        mTencent = Tencent.createInstance("1105655511", getApplicationContext());

        // 微博
        mAuthInfo = new AuthInfo(
                getApplicationContext(),
                "4216978203",
                "http://bbs.xianjichina.com/",
                "email,direct_messages_read,direct_messages_write,"
                        + "friendships_groups_read,friendships_groups_write,statuses_to_me_read,"
                        + "follow_app_official_microblog," + "invitation_write");

        ImageLoaderConfiguration config = new ImageLoaderConfiguration
                .Builder(getApplicationContext())
                .memoryCacheExtraOptions(480, 800)
                // max width, max height
                .threadPoolSize(3)
                // 线程池内加载的数量

                .threadPriority(Thread.NORM_PRIORITY - 2)
                // //降低线程的优先级保证主UI线程不受太大影响
                .denyCacheImageMultipleSizesInMemory()
                // 解码图像的大尺寸将在内存中缓存先前解码图像的小尺寸。
                .memoryCache(new LruMemoryCache(5 * 1024 * 1024))
                // 建议内存设在5-10M,可以有比较好的表现
                .memoryCacheSize(5 * 1024 * 1024)
                .discCacheSize(50 * 1024 * 1024)
                .discCacheFileNameGenerator(new Md5FileNameGenerator())// 设置磁盘缓存文件名称
                .tasksProcessingOrder(QueueProcessingType.LIFO)// 设置加载显示图片队列进程
                .discCacheFileCount(100) // 缓存的文件数量

                .writeDebugLogs() // Remove for release app
                .build();
        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config);
    }

    public static RequestQueue getHttpQueues() {
        return queues;
    }

    public static IWXAPI getApi() {
        return api;
    }

    public static Tencent getTencent() {
        return mTencent;
    }

//    private RefWatcher setupLeakCanary() {
//        if (LeakCanary.isInAnalyzerProcess(this)) {
//            return RefWatcher.DISABLED;
//        }
//        return LeakCanary.install(this);
//    }
//
//    public static RefWatcher getRefWatcher(Context context) {
//        XJApplication xjApplication = (XJApplication) context.getApplicationContext();
//        return xjApplication.mRefWatcher;
//    }

    /**
     * 程序崩溃检测
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        Intent intent = new Intent(this,MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);

        /** 杀死进程 **/
        android.os.Process.killProcess(android.os.Process.myPid());
        /** 终止当前正在运行的Java虚拟机，导致程序终止 **/
        System.exit(0);
        System.gc();
    }
}
